import {observable} from 'mobx';
import MacvonSys from '@/device/sys';
import {checkUpdate} from '@/util/apis';
import {
    upgrade,
    addDownLoadListener,
    addDownLoadSuccessListener,
} from '@/device/upgrade';
import {getUniqueId, getVersion} from 'react-native-device-info';

class SysStore {
    @observable list = [];
    @observable updating = false;
    @observable progress = 0;

    reboot = () => {
        MacvonSys.reboot();
    };

    weakUp = () => {
        MacvonSys.weakUp();
    };

    installApp = (apkPath) => {
        MacvonSys.installApp(apkPath);
    };

    powerOff = () => {
        MacvonSys.powerOff();
    };

    checkVersion = async () => {
        if (this.updating) {
            return;
        }
        const res = await checkUpdate();
        console.log('checkVersion ', res);
        console.log('getVersion ', getVersion());

        if (res.currentVersion.toString() !== getVersion()) {
            if (this.updating) {
                return;
            }
            upgrade(res.apkFile);
            this.updating = true;
            addDownLoadSuccessListener((apkFile) => {
                this.updating = false;
                this.installApp(apkFile);
                console.log(`下载完成`);
            });
            addDownLoadListener((current) => {
                this.progress = current;
                console.log(`正在下载 ${current}`);
            });
        } else {
            console.log('lastest version: ' + res.currentVersion);
        }
    };
}

const sysStore = new SysStore();
export default sysStore;
